package com.offcn.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.offcn.order.dao.OrderItemMapper;
import com.offcn.order.dao.OrderMapper;
import com.offcn.order.dao.PayLogMapper;
import com.offcn.order.entity.Cart;
import com.offcn.order.pojo.Order;
import com.offcn.order.pojo.OrderItem;
import com.offcn.order.pojo.PayLog;
import com.offcn.order.service.OrderService;
import com.offcn.sellergoods.feign.ItemFeign;
import com.offcn.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private OrderItemMapper orderItemMapper;

    @Autowired(required = false)
    private PayLogMapper payLogMapper;

    @Autowired
    private ItemFeign itemFeign;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void add(Order order) {
        // 1.获取购物车列表的数据
        String username = order.getUserId();
        String cartListStr = (String) stringRedisTemplate.boundHashOps("cartList").get(username);
        List<Cart> cartList = JSON.parseArray(cartListStr, Cart.class);

        // 2.创建订单数据，并写入到数据
        BigDecimal totalPayment = new BigDecimal(0);
        List<String> orderIds = new ArrayList<>();
        if(!CollectionUtils.isEmpty(cartList)) {
            for (Cart cart : cartList) {
                // 订单ID
                long orderId = new IdWorker(1, 1).nextId();// workerId表示订单服务器的ID，datacenter表示订单模块的id
                order.setOrderId(orderId);
                // 前端提交的数据 有支付金额，支付方式，收件人地址，收件人姓名，收件人手机号 已经在order封装好了
                // 自动确认的字段
                order.setStatus("1"); //未支付
                order.setUpdateTime(new Date()); // 修改时间
                order.setCreateTime(new Date()); // 创建时间
                // 购物车提供的字段
                order.setSellerId(cart.getSellerId());
                // 支付金额 进行计算
                BigDecimal orderPayment = new BigDecimal(0);
                // 3.创建订单选项数据，并写入到数据库
                for (OrderItem orderItem : cart.getOrderItemList()) {
                    long orderItemId = new IdWorker(1, 2).nextId();
                    orderItem.setId(orderItemId);
                    orderItem.setOrderId(orderId);
                    orderPayment = orderPayment.add(orderItem.getTotalFee());

                    orderItemMapper.insert(orderItem);

                }
                order.setPayment(orderPayment);
                totalPayment = totalPayment.add(orderPayment);
                orderIds.add(orderId + "");
                orderMapper.insert(order);
            }


            //4 减库存
            itemFeign.decrNum();

            // 5.只要是线上支付，则生成支付日志
            if ("1".equals(order.getPaymentType())) {  // 1 表示在线支付
                PayLog payLog = new PayLog();
                String payLogId = new IdWorker().nextId() + "";
                payLog.setOutTradeNo(payLogId);
                payLog.setCreateTime(new Date());
                payLog.setTotalFee(totalPayment.longValue());
                payLog.setUserId(username);
                payLog.setTradeState("0"); // 未支付
                payLog.setPayType(order.getPaymentType());
                // ["1234234134","45234134"]  => "1234234134","45234134"
                String orderIdsStr = orderIds.toString().replace("[", "").replace("]", "").replace(" ", "");
                payLog.setOrderList(orderIdsStr);
                // 写入数据库
                payLogMapper.insert(payLog);
                // 存储到redis中
                String str = JSON.toJSONString(payLog);
                stringRedisTemplate.boundHashOps("payLog").put(username, str);
            }

            // 6.清除购物车数据
            stringRedisTemplate.boundHashOps("cartList").delete(username);

        }

    }


    @Override
    public void updateStatus( String out_trade_no,String trade_no) {
        // 修改支付日志的数据
        PayLog payLog = payLogMapper.selectById(out_trade_no);
        payLog.setPayTime(new Date());
        payLog.setTransactionId(trade_no);;
        payLog.setTradeState("1");
        payLogMapper.updateById(payLog);
        // 修改订单数据
        // "123413413,1341234134,1345634563"
        String orderListStr = payLog.getOrderList();
        String[] orderIds = orderListStr.split(",");
        for (String orderId : orderIds) {
            Order order = orderMapper.selectById(Long.parseLong(orderId));
            order.setStatus("2"); // 已支付
            order.setPaymentTime(new Date()); // 支付时间
            orderMapper.updateById(order);
        }

        // 请求 redis 中 payLog 的数据
        stringRedisTemplate.boundHashOps("payLog").delete(payLog.getUserId());


    }
}
